function compressImage(file) {
  // 不压缩gif
  const fileType = file.type;
  if (fileType.includes("gif")) {
    return file;
  }

  return new Promise((resolve) => {
    new Compressor(file, {
      success(result) {
        resolve(result);
      },
    });
  });
}

const { createApp } = Vue;
const app = createApp({
  async mounted() {
    // 初始化编辑器
    CyueEditor.init(true);
    // 初始化 日期控件
    const inputDateElement = this.$refs.dateInput;
    inputDateElement.valueAsDate = new Date();

    // 判断登录
    this.accessToken = window.localStorage.getItem("token");
    if (!this.accessToken) {
      alert("未登录！");
      window.location.assign("./login.html");
    }

    // 判断 token 是否有效
    // axios.defaults.headers.common['token'] = this.accessToken;
    HTTP.setHeaders({
      token: this.accessToken,
    });
    HTTP.request({
      method: "GET",
      url: "/api/user/verifyToken",
    }).then((response) => {
      const result = response.data;
      if (!result.data) {
        window.localStorage.setItem("token", null);
        window.localStorage.setItem("username", null);
        alert("认证失效！请重新登录。");
        window.location.assign("./login.html");
      }
    });

    // 初始化 转载 checkbox
    document
      .getElementById("input-checkbox-reprint")
      .addEventListener("change", (e) => {
        const input = e.target;
        that.reprintCheck = input.checked;
        if (!input.checked) {
          document.getElementById("input-author").value = "";
        }
      });

    // 初始化 分类select
    HTTP.request({
      method: "GET",
      url: "/api/article/sort/all",
    }).then((response) => {
      const result = response.data;
      const sorts = result.data;
      const selectElement = this.$refs.sortSelect;
      sorts.forEach((element) => {
        const option = document.createElement("option");
        option.value = element.id;
        option.innerHTML = element.name;
        selectElement.appendChild(option);
      });
    });
  },

  data() {
    return {
      accessToken: null,
      currentPanel: "发布文章",
      reprintCheck: false,
      articleDataSource: [],
    };
  },

  methods: {
    clickArticleManage() {
      this.currentPanel = "文章管理";
      const username = window.localStorage.getItem("username");
      HTTP.request({
        method: "GET",
        url: `/api/article/user/username/${username}`,
      }).then(
        ((response) => {
          const result = response.data;
          this.articleDataSource = result.data;
        }).bind(this),
      );
    },

    clickSortManage() {
      this.currentPanel = "分类管理";
    },

    clickArticlePublish() {
      this.currentPanel = "发布文章";
    },

    async clickPublishArticle() {
      const editor = this.$refs.editor;
      // console.log(editor)

      const author = document.getElementById("input-author").value;
      const authorHomePage = document.getElementById(
        "input-author-homepage",
      ).value;
      const title = document
        .getElementsByClassName("panel-input-title")[0]
        .getElementsByTagName("input")[0].value;
      const date = document
        .getElementsByClassName("panel-input-date")[0]
        .getElementsByTagName("input")[0].value;
      const sortID = document
        .getElementsByClassName("panel-input-sort")[0]
        .getElementsByTagName("select")[0].value;
      let content = editor.getArticleContentXML();

      // debug
      // console.log(content);
      // return;

      if (!title) {
        alert("请输入标题");
        return;
      }
      if (!date) {
        alert("请输入日期");
        return;
      }
      if (!sortID) {
        alert("请选择分类");
        return;
      }
      if (!content) {
        alert("请输入正文内容");
        return;
      }
      if (content.length < 100) {
        alert("内容太少啦");
        return;
      }

      // 上传图片，替换 src
      const regexp = /<img [^>]*src=['"](?<src>[^'"]+)[^>]*>/gi;
      const regexpContent = content;
      let m = regexp.exec(regexpContent);
      let index = 1;
      let imgUpload = true;
      while (m) {
        // console.log(m);
        const src = m.groups.src;
        const base64RegexpResult = /data:(image\/[^;]*);base64,/.exec(src);
        const asciiData = src.replace(base64RegexpResult[0], "");
        let imgFormat = base64RegexpResult[1];
        const imgData = atob(asciiData);
        const imgBuffer = new Uint8Array(imgData.length);
        for (let i = 0; i < imgData.length; i++) {
          imgBuffer[i] = imgData.charCodeAt(i);
        }
        const imgBlob = new Blob([imgBuffer], {
          type: imgFormat,
        });
        const compressedImage = await compressImage(imgBlob);
        Dialog.popup(`上传第${index}张图片`);
        try {
          const response = await HTTP.request({
            method: "POST",
            url: "/api/resource/upload/img",
            headers: {
              token: this.accessToken,
              "Content-Type": "multipart/form-data",
            },
            data: {
              img: compressedImage,
            },
          });
          const result = response.data;
          if (result.type === "success") {
            Dialog.popup(`第${index}张图片上传成功`);
            const url = result.data;
            content = content.replace(src, url);
            imgUpload = true;
          } else {
            // console.log(result);
            Dialog.popup(`第${index}张图片上传失败`);
            imgUpload = false;
          }
        } catch (e) {
          Dialog.popup(`第${index}张图片上传失败`);
          imgUpload = false;
        }

        m = regexp.exec(regexpContent);
        index++;
      }

      // 有图片上传失败
      if (!imgUpload) {
        alert("发布失败");
        return;
      }

      HTTP.request({
        method: "POST",
        headers: {
          token: this.accessToken,
        },
        url: "/api/article",
        data: {
          sort_id: parseInt(sortID),
          author: author,
          author_home_page: authorHomePage,
          title: title,
          date: date,
          content_type: "xml",
          content: content,
        },
      }).then((response) => {
        const result = response.data;
        // console.log(result);
        if (result.type === "failure") {
          alert("发布失败");
          return;
        }

        alert("发布成功");
        editor.clear();
        document
          .getElementsByClassName("panel-input-title")[0]
          .getElementsByTagName("input")[0].value = "";
        document
          .getElementsByClassName("panel-input-date")[0]
          .getElementsByTagName("input")[0].value = "";
      });
    },
  },
});
app.mount("#app");
